﻿using AdminSystem.Application.Commands.lmgCommands;
using AdminSystem.Domain.Entities;
using AdminSystem.EntityFramworkCore;
using AdminSystem.Repositories.Interfaces;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace AdminSystem.Application.CommandHandlers.lmgCommandHandlers
{
    public class lmgAddCommandHandler : IRequestHandler<lmgAddCommand, APIResult<object>>
    {
        private readonly IBaseRepositories<Images> imagesBase;
        private readonly IBaseRepositories<ImagesMiddle> imagesMiddleBase;
        public lmgAddCommandHandler(IBaseRepositories<Images> imagesBase, IBaseRepositories<ImagesMiddle> imagesMiddleBase)
        {
            this.imagesBase = imagesBase;
            this.imagesMiddleBase = imagesMiddleBase;
        }
        public async Task<APIResult<object>> Handle(lmgAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Message = "添加成功";
            result.Codes = APIState.Success;

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    Images images = new Images();
                    images.ImgUrl = request.FileUrl;
                    await imagesBase.Add(images);

                    ImagesMiddle imagesMiddle = new ImagesMiddle();
                    imagesMiddle.ImgId = images.ImgId;
                    imagesMiddle.TheRestId = Convert.ToInt32(request.TheRestId);
                    await imagesMiddleBase.Add(imagesMiddle);
                    result.Data = images.ImgId.ToString();

                    scope.Complete();
                }
                catch (Exception exp)
                {
                    result.Data = exp.Message;
                    return await Task.FromResult(result);
                }

            }
            return await Task.FromResult(result);
        }
    }
}
